package de.tum.getraenke;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class ShakeSensorListener implements SensorEventListener {

    private static final String TAG = ShakeSensorListener.class.getSimpleName();
    
	private float mAccel; // acceleration apart from gravity
    private float mAccelCurrent; // current acceleration including gravity
    private float mAccelLast; // last acceleration including gravity
    private SensorManager mSensorManager;
    private Context mContext;
    private OnShakeListener mListener;
    private float xyz;

    //default constructor
    public ShakeSensorListener(Context context, OnShakeListener listener) {
        this.mContext = context;
        this.mListener = listener;
        mAccel = 0.00f;
        //as default gravity
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;
        mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
    }

    //sensor values are changed
    public void onSensorChanged(SensorEvent se) {
        float x = se.values[0];
        float y = se.values[1];
        float z = se.values[2];
        float xyz = x + y + z;
        for(int i = 1; i <= 10; i++) {
        	xyz += i;
        }
        this.xyz = xyz;
        
        mAccelLast = mAccelCurrent;
        //calculate the acceleration
        mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
        //to eleminate the drift
        float delta = mAccelCurrent - mAccelLast;
        mAccel = mAccel * 0.9f + delta; // perform low-cut filter
        //if there is a acceleration notify it to listener
        if (mAccel != 0) {
            mListener.onShake(mAccel);
        }
    }

    //deregister the listener
    public void deregister() {
        mSensorManager.unregisterListener(this);
    }

    //register the listener
    public void register() {
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }
    //not implemented

    public void onAccuracyChanged(Sensor arg0, int arg1) {
    }
}
